// src/store/websocket.js
import { defineStore } from 'pinia'

export const useWebsocketStore = defineStore('websocket', {
  state: () => ({
    websocket: null,
    isConnected: false,
    messages: [],
    messageListeners: [],
    reconnectAttempts: 0,
    maxReconnectAttempts: 5,
    shouldReconnect: true // 控制是否应该重连
  }),

  actions: {
    connectWebSocket (token = null) {
      // 如果已经连接，则先断开
      if (this.websocket) {
        this.disconnectWebSocket()
      }

      // 如果没有提供token，从localStorage获取
      const jwtToken = token || localStorage.getItem('token')

      // 如果没有token，不建立连接
      if (!jwtToken) {
        console.log('没有JWT令牌，无法建立WebSocket连接')
        return
      }

      let wsUrl = 'ws://localhost/api/chat/chatting'
      wsUrl += `?token=${encodeURIComponent(jwtToken)}`

      this.websocket = new WebSocket(wsUrl)

      this.websocket.onopen = () => {
        this.isConnected = true
        this.reconnectAttempts = 0
        console.log('WebSocket连接已建立')
      }

      this.websocket.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          // 将消息存储到状态中
          const message = {
            ...data,
            timestamp: new Date()
          }
          this.messages.push(message)
          console.log('收到WebSocket消息:', data)

          // 通知所有监听器
          this.messageListeners.forEach(callback => {
            callback(message)
          })
        } catch (error) {
          console.error('解析WebSocket消息失败:', error)
        }
      }

      this.websocket.onclose = () => {
        this.isConnected = false
        console.log('WebSocket连接已关闭')

        // 根据 shouldReconnect 决定是否重连
        if (this.shouldReconnect) {
          this.handleReconnect()
        } else {
          this.websocket = null
        }
      }

      this.websocket.onerror = (error) => {
        console.error('WebSocket错误:', error)
        // 错误时尝试重新连接
        this.handleReconnect()
      }
    },

    disconnectWebSocket () {
      // 设置 shouldReconnect 为 false，避免自动重连
      this.shouldReconnect = false

      if (this.websocket) {
        this.websocket.close()
        this.websocket = null
        this.isConnected = false
        this.reconnectAttempts = 0
      }
    },

    handleReconnect () {
      // 检查是否应该重连
      if (!this.shouldReconnect) {
        return
      }

      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        this.reconnectAttempts++
        console.log(`尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)

        // 延迟重连
        setTimeout(() => {
          const token = localStorage.getItem('token')
          if (token) {
            this.connectWebSocket(token)
          }
        }, 1000 * this.reconnectAttempts)
      } else {
        console.log('达到最大重连次数，停止重连')
      }
    },

    sendMessage (messageData) {
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(JSON.stringify(messageData))
        return true
      }
      console.warn('WebSocket未连接，无法发送消息')
      return false
    },

    // 添加监听器方法
    addMessageListener (callback) {
      this.messageListeners.push(callback)
    },

    // 移除监听器方法
    removeMessageListener (callback) {
      const index = this.messageListeners.indexOf(callback)
      if (index > -1) {
        this.messageListeners.splice(index, 1)
      }
    },

    // 重置连接状态（登出时调用）
    resetConnection () {
      this.disconnectWebSocket()
      this.messages = []
      this.messageListeners = []
      this.reconnectAttempts = 0
      this.shouldReconnect = true // 重置重连标志
    }
  }
})
